package appserver;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.Cookie;
/**
 * All utility functions for my servlet
 * @author Jose
 *
 */
public class ServletUtils {
	
	public static String headWithTitle(String title) {
	    return("<!DOCTYPE html>\n" +
	           "<html>\n" +
	           "<head><title>" + 
	            title + "</title></head>\n");
	}
	
	public static String formatDate(long millis) {
		SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss");
		Date resultdate = new Date(millis);
		return sdf.format(resultdate);
	}
	
	public static String generateForm(String method, String param, String value, String type, boolean hasTextIn) {
		String form =   "<form method" + "=" + method + ">" +
						"<input type=" + type + " name=" + param + " value=" + value + ">"; 				
		if (hasTextIn) {
			form += "<input type=text name=NewText size=40 maxlength=512>";
		}
		form += "</form>";
		return form;
	}
	
	public static Cookie getCookie(String name, Cookie[] cookies) {
		if (cookies == null) {
			return null;
		}
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(name))
				return cookie;
		}
		return null;
	}

	public static int getRandomNumber(int first, int last) {
		double rand = Math.random();
		int range = (int) ((last - first) * rand);
		int port = first + range;
		return port;
	}
}
